<?php

namespace App\Models\System;

use App\Models\Logs\ActivityLog;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Sites extends Model
{
    public const CACHE_PREFIX = 'SystemConfig:';
    protected $table = 'system_sites';
    protected $fillable = ['key', 'value'];
    /**
     * @param string $key
     * @return array
     */
    public static function GetPluginSet(string $key): array
    {
        if (!empty($key)) {
            return Cache::remember(self::CACHE_PREFIX.$key, Carbon::now()->addHours(2), static function () use ($key) {
                $data = self::query()->where('key', $key)->value('value');
                return !empty($data) ? json_decode($data, true) : [];
            });
        }
        return [];
    }

    /**
     * @param string $key
     * @param array $values
     * @return bool
     */
    public static function UpdatePluginSet(string $key, array $values = []): bool
    {
        if (!empty($key)) {
            DB::transaction(static function () use ($key, $values) {
                $model = self::query()->updateOrCreate(["key" => $key], ["value" => json_encode($values)]);
                ActivityLog::createSyslog('更新配置KEY：'.$key, $model);
                Cache::forget(self::CACHE_PREFIX.$key);
            });
            return true;
        }
        return false;
    }

}
